<!-- 代码编辑 -->
<template>
    <el-container>
        <el-header class="code-nav">
            <div class="code">
                <svg class="icon" aria-hidden="true">
                    <use xlink:href="#icon-daimabeifen"></use>
                </svg>
                代码
            </div>
        </el-header>

        <div class="select">
            <div class="lang-select">
                <el-select v-model="selectedLanguage" style="width: 100px" @change="selectChange()">
                    <el-option v-for="lang in languages" :key="lang" :value="lang">
                        {{ lang }}
                    </el-option>
                </el-select>
            </div>
            <div class="set">
                <svg class="icon" ref="setting" aria-hidden="true" style="width: 20px;height: 20px;">
                    <use xlink:href="#icon-setting"></use>
                </svg>
                <el-popover trigger="click" :virtual-ref="setting" :width="240" placement="bottom-end" :hide-after="50">
                    <el-row style="margin-bottom: 10px;">
                        <el-text style="margin-right: 20px;">切换主题</el-text>
                        <el-button v-for="theme in themes" :key="theme.key" :lable="theme.key" :value="theme.value"
                            @click="changeTheme(theme.value)">
                            {{ theme.key }}
                        </el-button>
                    </el-row>
                    <el-row>
                        <el-text style="margin-right: 20px;">字体大小</el-text>
                        <el-select v-model="selectedFontSize" @change="changeFontSize()" style="width:132px">
                            <el-option v-for="fontSize in fontSizes" :key="fontSize" :label="fontSize + 'px'"
                                :value="fontSize" :placeholder="selectedFontSize">
                            </el-option>
                        </el-select>
                    </el-row>
                </el-popover>
            </div>
            <div class="reset" @click="reset(selectedLanguage)">
                <svg class="icon" aria-hidden="true" style="width: 18px;height: 18px;">
                    <use xlink:href="#icon-reset"></use>
                </svg>
            </div>
        </div>
        <el-main style="padding: 0;">
            <div id="codeContainer"></div>
        </el-main>

        <el-footer style="height: 40px;">
            <div class="footer-container">
                <el-button type="primary" plain @click="toProblemList()">
                    返回题库
                </el-button>
                <el-button type="primary" @click="submit()">
                    提交
                </el-button>
            </div>
        </el-footer>
    </el-container>


</template>

<script setup>
import { onMounted, ref, toRaw } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useProblemStore } from '@/stores/problem'
import { useUserStore } from '@/stores/user'
import * as monaco from 'monaco-editor'
import { ElMessage } from 'element-plus'
import { addSubmissionAPI } from '@/apis/problem'

const problemStore = useProblemStore()
const userStore = useUserStore()

const router = useRouter()
const route = useRoute()
const editor = ref(null)
const themes = [
    {
        key: '浅色',
        value: 'vs',
    },
    {
        key: '深色',
        value: 'vs-dark',
    }
]

const selectedFontSize = ref(16)
const fontSizes = [12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]
const selectedLanguage = ref("C++")
const languages = [
    "C++",
    "Java",
    "Python3"
]

const setting = ref()

onMounted(() => {
    const path = useRoute().fullPath.split('/')
    problemStore.getProblem(`/${path[1]}/${path[2]}/description`).then(() => {
        initEditor('cpp', problemStore.problem.header.cpp_header)
    }).catch(() => {
        initEditor('cpp', '')
    })
})

// 初始化编辑器
function initEditor(defaultLanguage, defaultHeader) {
    editor.value = monaco.editor.create(document.querySelector('#codeContainer'), {
        value: defaultHeader, //编辑器初始显示文字
        theme: 'vs',
        language: defaultLanguage,
        overviewRulerBorder: false, // 滚动是否有边框
        minimap: {
            enabled: false,
        },
        fontSize: 16,
        selectOnLineNumbers: true, //显示行号
        automaticLayout: true, //自适应,
        suggest: {
            // 配置自动补全
            showWords: true, // 显示单词级别的自动补全建议
            showVariables: true, // 显示变量级别的自动补全建议
            showFunctions: true, // 显示函数级别的自动补全建议
            showMethods: true, // 显示方法级别的自动补全建议
            showClasses: true, // 显示类级别的自动补全建议
        },
        scrollbar: {
            verticalScrollbarSize: 8, // 垂直滚动条宽度，默认px
            horizontalScrollbarSize: 8 // 水平滚动条高度
        },
    })
}


// 重置代码
function reset(language) {
    if (language === "C++") {
        toRaw(editor.value).setValue(problemStore.problem.header.cpp_header)
    } else if (language === "Java") {
        toRaw(editor.value).setValue(problemStore.problem.header.java_header)
    } else if (language === "Python3") {
        toRaw(editor.value).setValue(problemStore.problem.header.python3_header)
    } else {
        toRaw(editor.value).setValue(problemStore.problem.header.cpp_header)
    }
}

// 切换主题
function changeTheme(theme) {
    monaco.editor.setTheme(theme)
}

// 切换字体大小
function changeFontSize() {
    const fontSize = selectedFontSize.value;

    editor.value.updateOptions({ fontSize });
}

// 检测语言切换
function selectChange() {
    if (selectedLanguage.value === "C++") {
        monaco.editor.setModelLanguage(toRaw(editor.value).getModel(), 'cpp')
    } else if (selectedLanguage.value === "Java") {
        monaco.editor.setModelLanguage(toRaw(editor.value).getModel(), 'java')
    } else if (selectedLanguage.value === "Python3") {
        monaco.editor.setModelLanguage(toRaw(editor.value).getModel(), 'python')
    } else {
        monaco.editor.setModelLanguage(toRaw(editor.value).getModel(), 'cpp')
    }
    reset(selectedLanguage.value)
}

// 返回题库
function toProblemList() {
    router.push("/problemlist")
}

// 提交代码
function submit() {
    // 先检查是否登录
    if (userStore.userInfo.token.length === 0) {
        // 没有登录
        ElMessage({ type: "warning", message: "请先登录" })
    } else {
        // 获取相关信息
        const submissionDetail = {
            "problem_id": problemStore.problem.id,
            "language": selectedLanguage.value,
            "code": toRaw(editor.value).getValue(),
            "cpu_limit": problemStore.problem.cpu_limit,
            "mem_limit": problemStore.problem.mem_limit,
        }
        console.log(submissionDetail)
        const path = route.fullPath.split("/")
        addSubmissionAPI("/problem/submission", submissionDetail).then((res) => {
            if (res.code === 0) {
                // 跳转到提交记录页面
                console.log(path[3])
                if (path[3] === "submitrecord") {
                    window.location.reload()
                } else {
                    router.push(`/${path[1]}/${path[2]}/submitrecord`)

                }
            }
        })
    }

}

</script>

<style scoped lang="scss">
.code-nav {
    border-radius: 10px 10px 0 0;
    background-color: #fafafa;
    height: 35px;
}

.code-nav .code {
    font-size: 16px;
    padding: 5px 10px;
}

.code-nav .code i {
    margin-right: 5px;
}

.select {
    padding: 0 15px;
    padding-bottom: 3px;
    background-color: #ffffff;
}

.lang-select {
    float: left;
}

.set {
    float: right;
    padding: 4px 0 0 0;
    margin-left: 15px;
    cursor: pointer;
}

.reset {
    float: right;
    padding: 5px 0;
    cursor: pointer;
}

.selected {
    background-color: blue;
    color: white;
}

#codeContainer {
    width: 100%;
    height: 100%;
}

.footer-container {
    margin-top: 5px;
    display: flex;
    justify-content: space-between;
}
</style>